package cn.zldemo.util;

import java.lang.reflect.Field;

import android.view.View;
import android.widget.AbsListView;

public class SetOnClickUtil {
	public static void registerOnClick(View.OnClickListener listener) {
		registerOnClick(listener, listener.getClass());
	}

	public static void registerOnClick(View.OnClickListener listener, Class<?> clazz) {
		Field[] fields = clazz.getDeclaredFields();

		ViewMapping viewMapping;
		for (Field field : fields) {
			viewMapping = field.getAnnotation(ViewMapping.class);
			if (viewMapping != null) {
				try {
					field.setAccessible(true);
					if (View.class.isAssignableFrom(field.getType())) {
						View v = (View) field.get(listener);
						if (v != null && !(v instanceof AbsListView)) {
							v.setOnClickListener(listener);
						}
					}
				} catch (Exception e) {
					throw new RuntimeException(field.getName() + " setOnClickListener error : " + e.getMessage());
				}
			}
		}
	}
}
